# 站长素材官网： https://sc.chinaz.com/

# 1.获取网页的源码
# 2.解析 解析的服务器响应的文件 etree.HTML
# 3.打印

# 需求 下载前十页图片
#
# https://sc.chinaz.com/tupian/nvshengtupian.html
# https://sc.chinaz.com/tupian/nvshengtupian_2.html
# https://sc.chinaz.com/tupian/nvshengtupian_6.html
import urllib.request
from lxml import etree


def create_request(page):
    if (page == 1):
        url = 'https://sc.chinaz.com/tupian/nvshengtupian.html'
    else:
        url = 'https://sc.chinaz.com/tupian/nvshengtupian_' + str(page) + '.html'

    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36'
    }
    request = urllib.request.Request(url=url, headers=headers)
    return request


def get_content(html_str):
    res = urllib.request.urlopen(html_str)
    content = res.read().decode('utf-8')
    return content


def down_load(content):
    # print(content)
    tree = etree.HTML(content)
    img_list = tree.xpath("//div/img/@data-original")
    name_list = tree.xpath("//div/img/@alt")
    HD_list = tree.xpath("//div[contains(@class,'tupian-list')]/div/div/a/@href")
    for i in range(len(img_list)):
        img_url = "https:" + img_list[i]
        img_name = name_list[i] + '.jpg'
        print('正在下载：' + img_name + "，其图片路劲是：" + img_url + '......')
        print('HD链接：https://sc.chinaz.com' + HD_list[i] + "......")
        HD_res = create_HD_request(HD_list, i)  # 获取HD链接
        HD_src = get_HD_src(HD_res)
        urllib.request.urlretrieve(HD_src, "./images/"+img_name)  # 下载高清图片


def create_HD_request(HD_list, page):
    url = 'https://sc.chinaz.com' + HD_list[page]
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36'
    }
    request = urllib.request.Request(url=url, headers=headers)
    return request


def get_HD_src(html_str):
    res = urllib.request.urlopen(html_str)
    content = res.read().decode('utf-8')
    tree = etree.HTML(content)
    content = tree.xpath("//div[contains(@class,'img-box')]/img/@src")
    return "https:"+content[0]


if __name__ == '__main__':
    start_page = int(input("请输入起始页码："))
    end_page = int(input("请输入结束页码："))
    for page in range(start_page, end_page + 1):
        print("当前正在下载第：" + str(page) + "页......")
        request = create_request(page)  # 返回请求对象
        content = get_content(request)  # 返回网页源码
        down_load(content)
